<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能考试系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- 引入lamejs库用于MP3编码 -->
    <script src="https://cdn.jsdelivr.net/npm/lamejs@1.2.0/lame.all.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Microsoft YaHei', sans-serif;
        }
        
        body {
            background-color: #f5f7fa;
            color: #333;
            line-height: 1.6;
        }
        
        .container {
            max-width: 900px;
            margin: 30px auto;
            padding: 20px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            position: relative;
        }
        
        .header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid #eee;
            position: relative; /* 为退出按钮定位 */
        }
        
        .header h1 {
            color: #2c3e50;
            margin-bottom: 10px;
        }
        
        /* 新增：退出考试按钮样式 */
        .exit-exam-btn {
            position: absolute;
            top: 20px;
            right: 20px;
            padding: 8px 16px;
            background-color: #f39c12;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .exit-exam-btn:hover {
            background-color: #e67e22;
        }
        
        .progress-bar {
            height: 10px;
            background: #ecf0f1;
            border-radius: 5px;
            margin: 15px 0;
            overflow: hidden;
        }
        
        .progress {
            height: 100%;
            background: #3498db;
            width: 0%;
            transition: width 0.3s ease;
        }
        
        .question-container {
            margin-bottom: 25px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #3498db;
        }
        
        .question-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 15px;
        }
        
        .question-number {
            background: #3498db;
            color: white;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 14px;
        }
        
        .question-content {
            font-size: 16px;
            line-height: 1.7;
        }
        
        .answer-container {
            margin-bottom: 20px;
        }
        
        .answer-container h3 {
            margin-bottom: 10px;
            color: #2c3e50;
        }
        
        textarea {
            width: 100%;
            height: 150px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
            resize: vertical;
            font-size: 15px;
        }
        
        textarea:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
        }
        
        .btn-container {
            display: flex;
            gap: 15px;
            margin-top: 20px;
        }
        
        .btn {
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 15px;
            font-weight: 500;
            transition: all 0.3s;
            border: none;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .btn-primary {
            background: #3498db;
            color: white;
            flex: 1;
        }
        
        .btn-primary:hover {
            background: #2980b9;
        }
        
        .btn-secondary {
            background: #ecf0f1;
            color: #7f8c8d;
        }
        
        .btn-secondary:hover {
            background: #d5dbdb;
        }
        
        .btn-warning {
            background: #f39c12;
            color: white;
        }
        
        .btn-warning:hover {
            background: #d35400;
        }
        
        .result-container {
            margin-top: 30px;
            padding: 20px;
            background: #e8f4fc;
            border-radius: 8px;
            display: none;
            position: relative;
            padding-bottom: 70px;
        }
        
        .result-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 15px;
        }
        
        .score {
            font-size: 24px;
            font-weight: bold;
            color: #2c3e50;
        }
        
        .feedback {
            background: white;
            padding: 15px;
            border-radius: 5px;
            margin-top: 15px;
        }
        
        .loading {
            text-align: center;
            padding: 20px;
            display: none;
        }
        
        .spinner {
            border: 4px solid rgba(0, 0, 0, 0.1);
            width: 36px;
            height: 36px;
            border-radius: 50%;
            border-left-color: #3498db;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
        }
        
        .total-score-container {
            background: #e8f4fc;
            border-radius: 8px;
            padding: 20px;
            margin-top: 20px;
            display: none;
        }
        
        .total-score-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 15px;
        }
        
        .total-score {
            font-size: 28px;
            font-weight: bold;
            color: #27ae60;
        }
        
        .question-scores {
            margin-top: 15px;
            background: white;
            padding: 15px;
            border-radius: 5px;
        }
        
        .score-item {
            display: flex;
            justify-content: space-between;
            padding: 5px 0;
            border-bottom: 1px solid #eee;
        }
        
        .score-item:last-child {
            border-bottom: none;
        }
        
        .next-btn-container {
            position: absolute;
            bottom: 15px;
            right: 15px;
        }
        
        .next-btn {
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 15px;
            font-weight: 500;
            transition: all 0.3s;
            border: none;
            display: flex;
            align-items: center;
            gap: 8px;
            background: #27ae60;
            color: white;
        }
        
        .next-btn:hover {
            background: #219653;
        }

        /* 修改语音输入和声纹录音为一个按钮控制 */
        .voice-control-container {
            margin-top: 15px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 5px;
            border: 1px solid #eee;
        }
        
        .voice-control-title {
            font-weight: bold;
            margin-bottom: 10px;
            color: #2c3e50;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .voice-control-buttons {
            display: flex;
            gap: 10px;
            margin-bottom: 10px;
        }
        
        .voice-record-btn {
            flex: 1;
            padding: 10px 15px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
            border: none;
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 5px;
            background: #dc3545;
            color: white;
        }
        
        .voice-record-btn.recording {
            background: #ffc107;
            color: #333;
        }
        
        .voice-record-btn:hover {
            opacity: 0.9;
        }
        
        .voice-status {
            display: flex;
            align-items: center;
            gap: 5px;
            margin-top: 10px;
            font-size: 14px;
        }
        
        .recording-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background-color: #dc3545;
            animation: pulse 1.5s infinite;
            display: none;
        }
        
        .audio-preview {
            margin-top: 15px;
            display: none;
        }
        
        @keyframes pulse {
            0% { transform: scale(0.95); opacity: 0.7; }
            50% { transform: scale(1.1); opacity: 1; }
            100% { transform: scale(0.95); opacity: 0.7; }
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        @media (max-width: 768px) {
            .container {
                margin: 15px;
                padding: 15px;
            }
            
            .btn-container {
                flex-direction: column;
            }
            
            .next-btn-container {
                position: static;
                margin-top: 20px;
                text-align: right;
            }
            
            /* 响应式调整退出按钮位置 */
            .exit-exam-btn {
                position: static;
                margin-top: 10px;
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>智能考试系统</h1>
            <p>大数据分析专业考试</p>
            <!-- 新增：退出考试按钮 -->
            <button class="exit-exam-btn" id="exit-exam-btn">
                <i class="fas fa-sign-out-alt"></i> 退出考试
            </button>
            <div class="progress-info">
                <span id="progress-text">0/0</span>
            </div>
            <div class="progress-bar">
                <div class="progress" id="progress-fill"></div>
            </div>
        </div>
        
        <div class="question-container">
            <div class="question-header">
                <h2>题目内容</h2>
                <div class="question-number">第 <span id="question-num">0</span> 题</div>
            </div>
            <div class="question-content" id="question-content">
                欢迎使用智能考试系统！点击下方按钮开始考试。
            </div>
        </div>
        
        <div class="answer-container" id="answer-container" style="display:none;">
            <h3><i class="fas fa-edit"></i> 您的答案</h3>
            <textarea id="answer-input" placeholder="请在此输入您的答案..."></textarea>
            
            <!-- 修改：合并语音输入和声纹录音为一个控制区域 -->
            <div class="voice-control-container">
                <div class="voice-control-title">
                    <i class="fas fa-microphone-alt"></i> 语音输入与声纹识别
                </div>
                <div class="voice-control-buttons">
                    <button class="voice-record-btn" id="voice-record-btn">
                        <i class="fas fa-microphone"></i> 开始录音
                    </button>
                </div>
                <div class="voice-status">
                    <div class="recording-indicator" id="recording-indicator"></div>
                    <span id="recording-status">准备就绪 - 点击按钮开始录音</span>
                </div>
                <div class="audio-preview" id="audio-preview">
                    <h6><i class="fas fa-headphones"></i> 录音预览</h6>
                    <audio id="audio-player" controls class="w-full"></audio>
                    <div class="text-sm text-muted mt-2">
                        <span>格式: MP3 | 采样率: 16kHz | 用于声纹验证</span>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="btn-container">
            <button class="btn btn-warning" id="human-intervene-btn" style="display:none;">
                <i class="fas fa-hands-helping"></i> 申请人工介入
            </button>
            <button class="btn btn-primary" id="submit-btn" style="display:none;">
                <i class="fas fa-paper-plane"></i> 提交答案
            </button>
            <button class="btn btn-primary" id="start-btn">
                <i class="fas fa-play"></i> 开始考试
            </button>
        </div>
        
        <div class="loading" id="loading">
            <div class="spinner"></div>
            <p>正在处理中，请稍候...</p>
        </div>
        
        <div class="result-container" id="result-container">
            <div class="result-header">
                <h3><i class="fas fa-chart-line"></i> 评分结果</h3>
                <div class="score"><span id="score-value">0</span>/10</div>
            </div>
            <div class="feedback">
                <h4><i class="fas fa-comment-alt"></i> 详细反馈</h4>
                <div id="feedback-content">
                    等待评分结果...
                </div>
            </div>
            
            <div class="next-btn-container">
                <button class="btn next-btn" id="next-btn" style="display:none;">
                    <i class="fas fa-arrow-right"></i> 下一题
                </button>
            </div>
        </div>
        
        <div class="total-score-container" id="total-score-container">
            <div class="total-score-header">
                <h3><i class="fas fa-trophy"></i> 考试总分</h3>
                <div class="total-score"><span id="total-score-value">0</span>/<span id="max-score-value">50</span></div>
            </div>
            
            <div class="question-scores" id="question-scores">
                <h4><i class="fas fa-list-ol"></i> 每题得分</h4>
                <div id="scores-list"></div>
            </div>
        </div>
    </div>

    <script>
        // 后端API基础URL
        const API_BASE_URL = 'http://127.0.0.1:5000';
        
        document.addEventListener('DOMContentLoaded', function() {
            const startBtn = document.getElementById('start-btn');
            const submitBtn = document.getElementById('submit-btn');
            const nextBtn = document.getElementById('next-btn');
            const resultContainer = document.getElementById('result-container');
            const answerContainer = document.getElementById('answer-container');
            const humanInterveneBtn = document.getElementById('human-intervene-btn');
            const questionNum = document.getElementById('question-num');
            const progressText = document.getElementById('progress-text');
            const progressFill = document.getElementById('progress-fill');
            const questionContent = document.getElementById('question-content');
            const loading = document.getElementById('loading');
            const scoreValue = document.getElementById('score-value');
            const feedbackContent = document.getElementById('feedback-content');
            const totalScoreContainer = document.getElementById('total-score-container');
            const totalScoreValue = document.getElementById('total-score-value');
            const maxScoreValue = document.getElementById('max-score-value');
            const scoresList = document.getElementById('scores-list');
            const exitExamBtn = document.getElementById('exit-exam-btn');
            
            // 语音输入和录音相关元素
            const voiceRecordBtn = document.getElementById('voice-record-btn');
            const recordingIndicator = document.getElementById('recording-indicator');
            const recordingStatus = document.getElementById('recording-status');
            const answerInput = document.getElementById('answer-input');
            const audioPreview = document.getElementById('audio-preview');
            const audioPlayer = document.getElementById('audio-player');
            
            let currentQuestion = 0;
            let maxQuestions = 0;
            let recognition = null;
            let isRecording = false;
            
            // 录音相关全局变量
            let audioContext;
            let mediaRecorder;
            let audioChunks = [];
            let mp3Blob = null;
            let username = localStorage.getItem('username') || 'default_user';
            let mediaStream = null;

            // ====================== 录音功能 ======================
            // 初始化音频上下文
            function initAudioContext() {
                if (!audioContext) {
                    try {
                        audioContext = new (window.AudioContext || window.webkitAudioContext)();
                    } catch (error) {
                        console.error('无法初始化 AudioContext:', error);
                        recordingStatus.textContent = '您的浏览器不支持音频录制功能';
                        voiceRecordBtn.disabled = true;
                    }
                }
            }
            
            // 开始录音（同时启动语音识别和MP3录音）
            function startRecording() {
                initAudioContext();
                
                // 重置状态
                audioChunks = [];
                mp3Blob = null;
                audioPreview.style.display = 'none';
                
                // 更新UI状态
                recordingIndicator.style.display = 'block';
                recordingStatus.textContent = '正在录音...请说话';
                voiceRecordBtn.classList.add('recording');
                voiceRecordBtn.innerHTML = '<i class="fas fa-stop"></i> 停止录音';
                
                // 请求麦克风权限
                navigator.mediaDevices.getUserMedia({ audio: true })
                    .then(stream => {
                        mediaStream = stream;
                        
                        // 启动语音识别
                        startSpeechRecognition();
                        
                        // 创建MediaRecorder
                        mediaRecorder = new MediaRecorder(stream);
                        
                        // 监听数据可用事件
                        mediaRecorder.addEventListener('dataavailable', event => {
                            audioChunks.push(event.data);
                        });
                        
                        // 监听录音停止事件
                        mediaRecorder.addEventListener('stop', () => {
                            const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
                            convertToMp3(audioBlob).then(mp3Blob => {
                                // 存储处理后的MP3
                                window.mp3Blob = mp3Blob;
                                
                                // 创建音频URL并设置预览
                                const audioUrl = URL.createObjectURL(mp3Blob);
                                audioPlayer.src = audioUrl;
                                audioPreview.style.display = 'block';
                                
                                recordingStatus.textContent = '录音完成，可点击播放预览';
                            }).catch(error => {
                                console.error('MP3转换失败:', error);
                                recordingStatus.textContent = 'MP3转换失败，请重试';
                            });
                        });
                        
                        // 开始录音
                        mediaRecorder.start();
                    })
                    .catch(error => {
                        console.error('录音错误:', error);
                        recordingStatus.textContent = `录音失败: ${error.message}`;
                        resetRecordingButton();
                    });
            }
            
            // 停止录音（同时停止语音识别和MP3录音）
            function stopRecording() {
                if (mediaRecorder && mediaRecorder.state !== 'inactive') {
                    mediaRecorder.stop();
                }
                
                // 停止语音识别
                if (recognition) {
                    recognition.stop();
                    isRecording = false;
                }
                
                // 关闭录音流
                if (mediaStream) {
                    mediaStream.getTracks().forEach(track => track.stop());
                    mediaStream = null;
                }
                
                recordingIndicator.style.display = 'none';
                voiceRecordBtn.classList.remove('recording');
                voiceRecordBtn.innerHTML = '<i class="fas fa-microphone"></i> 开始录音';
            }
            
            // 重置录音按钮
            function resetRecordingButton() {
                voiceRecordBtn.classList.remove('recording');
                voiceRecordBtn.innerHTML = '<i class="fas fa-microphone"></i> 开始录音';
                recordingIndicator.style.display = 'none';
            }
            
            // 启动语音识别
            function startSpeechRecognition() {
                try {
                    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
                    if (!SpeechRecognition) {
                        console.error('浏览器不支持语音识别API');
                        recordingStatus.textContent = '浏览器不支持语音识别';
                        return;
                    }
                    
                    recognition = new SpeechRecognition();
                    recognition.continuous = true;
                    recognition.interimResults = true;
                    recognition.lang = 'zh-CN';
                    
                    recognition.onstart = function() {
                        isRecording = true;
                    };
                    
                    recognition.onerror = function(event) {
                        console.error('语音识别错误:', event.error);
                        recordingStatus.textContent = `识别错误: ${event.error}`;
                    };
                    
                    recognition.onend = function() {
                        if (isRecording) {
                            // 如果仍在录音状态但识别结束，则重新启动
                            recognition.start();
                        }
                    };
                    
                    recognition.onresult = function(event) {
                        let interimTranscript = '';
                        let finalTranscript = '';
                        
                        for (let i = event.resultIndex; i < event.results.length; i++) {
                            const transcript = event.results[i][0].transcript;
                            if (event.results[i].isFinal) {
                                finalTranscript += transcript;
                            } else {
                                interimTranscript += transcript;
                            }
                        }
                        
                        // 更新文本框内容
                        const currentText = answerInput.value;
                        answerInput.value = currentText + finalTranscript;
                        
                        // 如果是临时结果，可以显示在状态中
                        if (interimTranscript) {
                            recordingStatus.textContent = `识别中: ${interimTranscript}`;
                        } else if (finalTranscript) {
                            recordingStatus.textContent = '正在录音...';
                        }
                    };
                    
                    // 开始语音识别
                    recognition.start();
                } catch (error) {
                    console.error('语音识别初始化失败:', error);
                    recordingStatus.textContent = '语音识别初始化失败';
                }
            }
            
            // 将WAV转换为MP3
            function convertToMp3(audioBlob) {
                return new Promise((resolve, reject) => {
                    const reader = new FileReader();
                    reader.onload = function() {
                        const buffer = reader.result;
                        audioContext.decodeAudioData(buffer, function(decodedData) {
                            // 获取单声道数据
                            const samples = decodedData.getChannelData(0);
                            
                            // 创建MP3编码器
                            const mp3Encoder = new lamejs.Mp3Encoder(1, 16000, 128); // 单声道, 16kHz, 128kbps
                            const sampleBlockSize = 1152; // 每块采样数
                            const mp3Data = [];
                            
                            // 分块编码
                            for (let i = 0; i < samples.length; i += sampleBlockSize) {
                                const sampleChunk = samples.subarray(i, i + sampleBlockSize);
                                const mp3buf = mp3Encoder.encodeBuffer(sampleChunk);
                                if (mp3buf.length > 0) {
                                    mp3Data.push(mp3buf);
                                }
                            }
                            
                            // 结束编码
                            const mp3buf = mp3Encoder.flush();
                            if (mp3buf.length > 0) {
                                mp3Data.push(mp3buf);
                            }
                            
                            // 合并数据
                            const mergedArray = new Uint8Array(
                                mp3Data.reduce((acc, item) => [...acc, ...Array.from(item)], [])
                            );
                            
                            // 创建MP3 Blob
                            const mp3Blob = new Blob(mp3Data, { type: 'audio/mp3' });
                            resolve(mp3Blob);
                        });
                    };
                    reader.readAsArrayBuffer(audioBlob);
                });
            }
            
            // 绑定录音按钮事件
            voiceRecordBtn.addEventListener('click', function() {
                if (isRecording) {
                    stopRecording();
                } else {
                    startRecording();
                }
            });
            
            // ====================== 考试核心功能 ======================
            // 更新进度
            function updateProgress() {
                questionNum.textContent = currentQuestion;
                progressText.textContent = `${currentQuestion}/${maxQuestions}`;
                progressFill.style.width = `${(currentQuestion / maxQuestions) * 100}%`;
            }
            
            // 显示加载状态
            function showLoading() {
                loading.style.display = 'block';
            }
            
            // 隐藏加载状态
            function hideLoading() {
                loading.style.display = 'none';
            }
            
            // 处理API请求错误
            function handleApiError(error) {
                console.error('API请求错误:', error);
                hideLoading();
                alert(`请求失败: ${error.message || '未知错误'}`);
            }
            
            // 退出考试按钮点击事件
            exitExamBtn.addEventListener('click', function() {
                if (confirm('确定要退出考试吗？未完成的题目将不会保存。')) {
                    window.location.href = 'student_home.html';
                }
            });
            
            // 开始考试
            startBtn.addEventListener('click', function() {
                showLoading();
                
                fetch(`${API_BASE_URL}/start_exam`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    credentials: 'include'
                })
                .then(response => {
                    if (!response.ok) {
                        return response.json().then(errData => {
                            throw new Error(errData.error || `HTTP错误! 状态码: ${response.status}`);
                        });
                    }
                    return response.json();
                })
                .then(data => {
                    hideLoading();
                    if (data.error) {
                        throw new Error(data.error);
                    }
                    
                    questionContent.textContent = data.question;
                    currentQuestion = data.question_count;
                    maxQuestions = data.max_questions;
                    updateProgress();
                    
                    // 显示答题区域
                    answerContainer.style.display = 'block';
                    submitBtn.style.display = 'block';
                    humanInterveneBtn.style.display = 'block';
                    startBtn.style.display = 'none';
                    resultContainer.style.display = 'none';
                    totalScoreContainer.style.display = 'none';
                    
                    // 重置录音状态
                    resetRecordingButton();
                    recordingStatus.textContent = '准备录制音频';
                    audioPreview.style.display = 'none';
                    
                    // 滚动到题目区域
                    document.querySelector('.question-container').scrollIntoView({ behavior: 'smooth' });
                })
                .catch(handleApiError);
            });
            
            // 提交答案
            submitBtn.addEventListener('click', function() {
                const answer = answerInput.value.trim();
                
                if (!answer) {
                    alert('请输入答案后再提交');
                    return;
                }
                
                showLoading();
                
                // 创建FormData对象，用于同时发送文本答案和MP3文件
                const formData = new FormData();
                formData.append('answer', answer);
                formData.append('verify_feature_id', username);
                
                // 如果录制了MP3，添加到表单数据
                if (window.mp3Blob) {
                    formData.append('audio', window.mp3Blob, 'voiceprint.mp3');
                }
                
                fetch(`${API_BASE_URL}/submit_answer`, {
                    method: 'POST',
                    body: formData,
                    credentials: 'include'
                })
                .then(response => {
                    if (!response.ok) {
                        return response.json().then(errData => {
                            throw new Error(errData.error || `HTTP错误! 状态码: ${response.status}`);
                        });
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.error) {
                        throw new Error(data.error);
                    }
                    
                    // 显示评分结果
                    scoreValue.textContent = data.score.toFixed(1);
                    feedbackContent.textContent = data.feedback;
                    resultContainer.style.display = 'block';
                    
                    // 更新进度
                    currentQuestion = data.question_count;
                    updateProgress();
                    
                    // 处理追问情况
                    if (data.need_follow_up && data.follow_up_question) {
                        questionContent.textContent = data.follow_up_question;
                        answerInput.value = '';
                        nextBtn.style.display = 'none';
                    } else {
                        nextBtn.style.display = 'block';
                    }
                    
                    // 滚动到结果区域
                    resultContainer.scrollIntoView({ behavior: 'smooth' });
                })
                .catch(handleApiError)
                .finally(() => {
                    hideLoading();
                });
            });
            
            // 下一题
            nextBtn.addEventListener('click', function() {
                showLoading();
                
                fetch(`${API_BASE_URL}/next_question`, {
                    method: 'GET',
                    headers: {
                        'Accept': 'application/json'
                    },
                    credentials: 'include'
                })
                .then(response => {
                    if (!response.ok) {
                        return response.json().then(errData => {
                            throw new Error(errData.error || `HTTP错误! 状态码: ${response.status}`);
                        });
                    }
                    return response.json();
                })
                .then(data => {
                    hideLoading();
                    if (data.error) {
                        throw new Error(data.error);
                    }
                    
                    if (data.message) {
                        // 显示总分
                        totalScoreValue.textContent = data.total_score.toFixed(1);
                        maxScoreValue.textContent = data.max_possible_score;
                        totalScoreContainer.style.display = 'block';
                        
                        // 显示每题得分
                        scoresList.innerHTML = '';
                        data.question_scores.forEach((score, index) => {
                            const scoreItem = document.createElement('div');
                            scoreItem.className = 'score-item';
                            scoreItem.innerHTML = `
                                <span>第 ${index + 1} 题得分:</span>
                                <span>${score.toFixed(1)}/10</span>
                            `;
                            scoresList.appendChild(scoreItem);
                        });
                        
                        // 滚动到总分区域
                        totalScoreContainer.scrollIntoView({ behavior: 'smooth' });
                        
                        // 隐藏结果容器和下一题按钮
                        resultContainer.style.display = 'none';
                        nextBtn.style.display = 'none';
                    } else {
                        // 更新题目
                        questionContent.textContent = data.question;
                        answerInput.value = '';
                        resultContainer.style.display = 'none';
                        nextBtn.style.display = 'none';
                        
                        // 更新进度
                        currentQuestion = data.question_count;
                        updateProgress();
                        
                        // 重置录音状态
                        resetRecordingButton();
                        recordingStatus.textContent = '准备录制音频';
                        audioPreview.style.display = 'none';
                        
                        // 滚动到题目区域
                        document.querySelector('.question-container').scrollIntoView({ behavior: 'smooth' });
                        
                        // 焦点定位到答案输入框
                        answerInput.focus();
                    }
                })
                .catch(handleApiError);
            });
            
            // 申请人工介入
            humanInterveneBtn.addEventListener('click', function() {
                showLoading();
                
                fetch(`${API_BASE_URL}/request_human_intervention`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    credentials: 'include',
                    body: JSON.stringify({})
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP错误! 状态码: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    hideLoading();
                    if (data.error) {
                        throw new Error(data.error);
                    }
                    
                    alert(data.message);
                    console.log('人工介入上下文:', data.context);
                })
                .catch(handleApiError);
            });
            
            // 页面卸载时停止录音
            window.addEventListener('beforeunload', function() {
                if (isRecording) {
                    stopRecording();
                }
            });
        });
    </script>
</body>
</html>